package com.byit.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.byit.builder.MapBuilder;
import com.byit.constant.DefaultValue;
import com.byit.domain.SysCompany;
import com.byit.enums.PromptInfo;
import com.byit.msg.MessageResult;
import com.byit.service.ISysCompanyService;
import com.byit.shrio.session.SessionHelper;
import com.byit.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 公司表 前端控制器
 * </p>
 *
 * @author wangx
 * @since 2018-12-11
 */
@RestController
@RequestMapping("/api/sys/sysCompany")
public class SysCompanyController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ISysCompanyService sysCompanyService;

    /**
     * 新增或修改公司信息
     *
     * @param session
     * @param company
     * @return
     */
    @PostMapping("/save")
    public Object insertCompany(HttpSession session, SysCompany company) {
        Long userId = SessionHelper.getUserId(session);
        try {
            if (null == userId) {
                return MessageResult.warpper(PromptInfo.USER_LOGIN_INVALID);
            }
            if (null == company) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }
            company.setCreateTime(new Date());
            company.setOperationId(userId);
            sysCompanyService.insertOrUpdate(company);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }

    @PostMapping("/update")
    public Object updateCompany(HttpSession session, SysCompany company) {
        Long userId = SessionHelper.getUserId(session);
        try {
            if (null == userId) {
                return MessageResult.warpper(PromptInfo.USER_LOGIN_INVALID);
            }
            if (null == company) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }
            company.setUpdateTime(new Date());
            company.setOperationId(userId);
            sysCompanyService.insertOrUpdate(company);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }

    /**
     * 按照公司标识查询公司信息
     *
     * @param id
     * @return
     */
    @GetMapping("/selectById/{id}")
    public Object selectCompanyById(@PathVariable("id") Integer id) {
        SysCompany sysCompany = sysCompanyService.selectById(id);
        return MessageResult.success(sysCompany);
    }

    /**
     * 按照条件查询公司列表
     *
     * @param session
     * @param code
     * @param name
     * @param type
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public Object selectCompanyAll(HttpSession session,
                                   @RequestParam(value = "code", defaultValue = "") String code,
                                   @RequestParam(value = "name", defaultValue = "") String name,
                                   @RequestParam(value = "type", defaultValue = "") Integer type,
                                   @RequestParam(value = "page", defaultValue = DefaultValue.PAGE_FIRST) int page,
                                   @RequestParam(value = "limit", defaultValue = DefaultValue.PAGE_SIZE) int limit) {
        Page<SysCompany> pageInfo = new Page<>(page, limit);
        Map<String, Object> params = MapBuilder.newMap(3).ok();
        if (null != name && !"".equals(name)) {
            params.put("name", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(name) + "%");
        }
        if (null != code && !"".equals(code)) {
            params.put("code", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(code) + "%");
        }
        if (null != type) {
            params.put("type", type);
        }
        Page<JSONObject> result = sysCompanyService.selectCompanyAll(pageInfo, params);
        return MessageResult.warpper(PromptInfo.SYS_SECCUSS, result);
    }

    /**
     * 逻辑删除公司信息
     *
     * @param session
     * @param ids
     * @return
     */
    @PostMapping("/delete")
    public Object delCompanyByIds(HttpSession session, @RequestParam("ids") String ids) {
        Long companyId = SessionHelper.getCompanyId(session);
        Long userId = SessionHelper.getUserId(session);
        if (null == userId) {
            return MessageResult.warpper(PromptInfo.USER_LOGIN_INVALID);
        }
        List<Long> idList = StringUtil.splitLong(ids, ",");
        Map<String, Object> map = MapBuilder.newMap(3).setParam("updateTime", new Date()).setParam("operId", userId).ok();

        for (Long id : idList) {
            if (id == companyId) {
                return MessageResult.error(PromptInfo.ERROR_NOT_DELETE_USER_COMPANY);
            }
            map.put("id", id);
            sysCompanyService.delCompanyById(map);
        }
        return MessageResult.success();
    }

    @GetMapping("/selectMap")
    public Object selectMap(HttpSession session) {
        Long userId = SessionHelper.getUserId(session);
        if (null == userId) {
            return MessageResult.warpper(PromptInfo.USER_LOGIN_INVALID);
        }
        List<JSONObject> jsonObject = sysCompanyService.selectMap();
        return MessageResult.success(jsonObject);
    }

}
